package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BTermModelInfo;
import cc.rengu.redp.bizimpl.upmp.dao.BTermModelInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.BTermModelInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lizk
 */
@Service("bTermModelInfoService")
@DS("upmp")
public class BTermModelInfoServiceImpl extends ServiceImpl<BTermModelInfoMapper, BTermModelInfo> implements IBTermModelInfoService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private BTermModelInfoMapper bTermModelInfoMapper;
    @Value("${redp.max.batch.insert.num}")
    private int batchInsertMaxNum;
    @Autowired
    private IUpmpSysSeqService sysSeqService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;

    private long oprMenuId = 1;
    private String oprMenuName = "终端管理:终端型号管理";
    private long chkMenuId = 2;
    private String chkMenuName = "终端管理:终端型号审核";
    private String webNextUrl = "/modelAdmin";


    @Override
    public IPage<BTermModelInfo> findByPage(QueryRequest request, BTermModelInfoVO model) {
        try {
            LambdaQueryWrapper<BTermModelInfo> queryWrapper = new LambdaQueryWrapper<>();

            if (!StringUtils.isEmpty(model.getBrandCode())) {
                queryWrapper.eq(BTermModelInfo::getBrandCode, model.getBrandCode());
            }
            if (!StringUtils.isEmpty(model.getModelCode())) {
                queryWrapper.and(i -> i.like(BTermModelInfo::getModelCode, model.getModelCode())
                        .or().like(BTermModelInfo::getModelDesc, model.getModelDesc())
                        .or().like(BTermModelInfo::getModelName, model.getModelName()));
            }

            Page<BTermModelInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取型号信息失败", e);
            return null;
        }
    }

    @Override
    public void createModel(BTermModelInfoVO model) throws RedpException {

        String flag = model.getFlag();
        boolean result = checkModelNameAndCodeExist(model.getModelName(), null);
        if (result) {
            String message = "终端型号名重复,请重新填写";
            log.error(message);
            throw new RedpException(message);
        }
        //获取型号代码
        String modelcd = BusinessContainer.ModelCd_PREFIX + String.format("%06d", Integer.parseInt(sysSeqService
                .updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.ModelCd_PREFIX, null)));
        boolean result1 = checkModelNameAndCodeExist(null, modelcd);
        if (result1) {
            String message = "终端型号代码重复,请联系管理员";
            log.error(message);
            throw new RedpException(message);
        }

        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(model.getInstId(), "model:add");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        BTermModelInfo newModel = new BTermModelInfo();
        BeanUtils.copyProperties(model, newModel);

        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {
            //
            String opt = model.getOpt();
            if (Common.isBlank(opt)) {
                String message = "请求参数(opt)异常!";
                log.error(message);
                throw new RedpException(message);
            }
//            String bizOpr = "";

            String auditRefuseReason = model.getAuditRefuseReason();
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(newModel.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    newModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    newModel.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    newModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
//                bizOpr = BizOprEnum.OPR_ADD.getType();
            }
            newModel.setAuditRefuseReason(auditRefuseReason);
            this.save(newModel);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(newModel, newModel, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        newModel.getId(), null, null, null);

            }
            // 修改临时表的审核状态等字段
            //保存到临时表
            bizTmpService.saveBizTmp(newModel, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                    String.valueOf(chkMenuId), chkMenuName,
                    newModel.getStatus(), newModel.getAuditStatus(), newModel.getId(), "", null, null, null);

        } else {
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
                newModel.setOprId(user.getId());
                newModel.setBrandCode(model.getBrandCode());
                model.setModelCode(modelcd);
                //   entity.setCrtOrgId(org.getOrgCode());
                newModel.setCreateTime(lastUpddt);
                newModel.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                newModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(newModel);
                //保存到临时表
                bizTmpService.saveBizTmp(newModel, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        newModel.getStatus(), newModel.getAuditStatus(), newModel.getId(), "", null, null, null);

//            result.put("id", entity.getId());

            } else {

                //不需要审核
                newModel.setCreateTime(lastUpddt);
                newModel.setBrandCode(model.getBrandCode());
                newModel.setModelCode(modelcd);
                newModel.setCrtOrgId(user.getCrtOrgId());
                newModel.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                newModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(newModel);

                bizHisService.saveBizHisNew(newModel, newModel, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        newModel.getId(), null, null, null);

            }
        }

    }

    @Override
    public boolean checkModelNameAndCodeExist(String modelName, String modelCode) {
        LambdaQueryWrapper<BTermModelInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(modelName)) {
            queryWrapper.eq(BTermModelInfo::getModelName, modelName);
        }
        if (!StringUtils.isEmpty(modelCode)) {
            queryWrapper.eq(BTermModelInfo::getModelCode, modelCode);
        }

        int count = this.count(queryWrapper);
        if (count != 0) {
            //存在返回
            return true;
        } else {
            return false;
        }
    }

    @Override
    public BTermModelInfo findTermModel(String modelCode) {
        LambdaQueryWrapper<BTermModelInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BTermModelInfo::getModelCode, modelCode);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, Object> termmodelSelect2List(String q, QueryRequest request) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");

        String modelCodeOrName = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            modelCodeOrName = param[0];
        }
        String brandCode = "";
        if (null != param && param.length > 1) {
            if (Common.isNotBlank(param[1])) {
                brandCode = param[1];
            }
        }
        String instId = "";
        if (null != param && param.length > 2) {
            if (Common.isNotBlank(param[2])) {
                instId = param[2];
            }
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(instId)) {
            instId = user.getInstId();
        }
        try {
            LambdaQueryWrapper<BTermModelInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BTermModelInfo::getStatus, "01");
            queryWrapper.eq(BTermModelInfo::getInstId, instId);
            if (null != user && !user.isAdmin()) {
//                queryWrapper.in(BTermModelInfo::getSignInstId, Arrays.asList(GZIPUtils.uncompressToString(user.getUserOrgCodes()).split(",")));
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(brandCode)) {
                queryWrapper.eq(BTermModelInfo::getBrandCode, brandCode);
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(modelCodeOrName)) {
                String finalmodelCodeOrName = modelCodeOrName;
                queryWrapper.and(qw -> qw.likeRight(BTermModelInfo::getModelCode, finalmodelCodeOrName).or().likeRight(BTermModelInfo::getModelName, finalmodelCodeOrName));
            }
            queryWrapper.orderByDesc(BTermModelInfo::getCreateTime);
            Page<BTermModelInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<BTermModelInfo> page1 = this.page(page, queryWrapper);
            List<BTermModelInfo> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    BTermModelInfo org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getModelCode());
                    map.put("name", org.getModelName());
                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取终端型号信息失败", e);
            return null;
        }
    }

    @Override
    public void updateModel(BTermModelInfoVO model) throws RedpException {
        String flag = model.getFlag();
        String modelName = model.getModelName();
        if (Common.isBlank(model.getId())) {
            String message = "请求参数(id)异常!";
            log.error(message);
            throw new RedpException(message);
        }


        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(model.getInstId(), "model:update");
        BTermModelInfo db = baseMapper.selectById(model.getId());
        if (!db.getModelName().equals(modelName)) {
            boolean result = checkModelNameAndCodeExist(model.getModelName(), null);
            if (result) {
                String message = "终端型号名重复,请重新填写!";
                log.error(message);
                throw new RedpException(message);
            }
        }

        BeanUtils.copyProperties(model, db);
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");


        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(model.getId());
            if (Common.isBlank(tmp)) {
                String message = "根据id没有找到指定临时表数据!";
                log.error(message);
                throw new RedpException(message);
            }
//            String bizdata = "";
//            if (null != tmp.getBizData1()) {
//                bizdata += tmp.getBizData1();
//            }
//            if (null != tmp.getBizData2()) {
//                bizdata += tmp.getBizData2();
//            }
//            if (null != tmp.getBizData3()) {
//                bizdata += tmp.getBizData3();
//            }

//            BTermBrandInfo termBrandNew = JSON.parseObject(bizdata, BTermBrandInfo.class);

            // 备份正式表数据

            if (Common.isBlank(db)) {
                String message = "根据id没有找到指定数据!";
                log.error(message);
                throw new RedpException(message);
            }
            String opt = model.getOpt();
            if (Common.isBlank(opt)) {
                String message = "请求参数(opt)异常!";
                log.error(message);
                throw new RedpException(message);
            }
            //校验终端品牌名称不能重复
//            if (!result && "pass".equals(opt)) {
//                String message = "终端品牌名重复,请审核拒绝退回重新修改!";
//                log.error(message);
//                throw new RedpException(message);
//            }
//            if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(brand.getAuditStatus())) {
//                if (!PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
//
//                } else {
//                    BeanUtils.copyProperties(termBrandNew, termBrand);
//                }
//            } else {
//                BeanUtils.copyProperties(termBrandNew, termBrand);
//            }

            String auditRefuseReason = model.getAuditRefuseReason();
            if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(model.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    db.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    db.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    db.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
            }
            db.setAuditRefuseReason(auditRefuseReason);
            baseMapper.updateById(db);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(db, db, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        db.getId(), null, null, null);
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(db, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(chkMenuId), chkMenuName,
                    db.getStatus(), db.getAuditStatus(), db.getId(), "", null, null, null);
        } else {

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
                db.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                db.setLastOprId(user.getId());
                db.setLastUpdateTime(lastUpddt);
                baseMapper.updateById(db);

                bizTmpService.saveBizTmp(db, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        db.getStatus(), db.getAuditStatus(), db.getId(), "", null, null, null);

            } else {
                db.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                db.setLastOprId(user.getId());
                db.setLastUpdateTime(lastUpddt);
                baseMapper.updateById(db);

                bizHisService.saveBizHisNew(db, db, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        db.getId(), null, null, null);
            }
        }

    }

    @Override
    public List<BTermModelInfo> findTests() {
        try {
            return baseMapper.selectList(new QueryWrapper<BTermModelInfo>().orderByDesc("CREATE_TIME"));
        } catch (Exception e) {
            log.error("获取信息失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public void batchInsert(List<BTermModelInfoVO> list, String brandCode) throws RedpException {
        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(list.get(0).getInstId(), "model:add");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");

        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {

            for (int i = 0; i < list.size(); i++) {
                BTermModelInfo newModel = new BTermModelInfo();
                BeanUtils.copyProperties(list.get(i), newModel);
                //获取品牌代码
                String modelCode = BusinessContainer.ModelCd_PREFIX + String.format("%06d", Integer.parseInt(sysSeqService
                        .updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.ModelCd_PREFIX, null)));

                newModel.setModelCode(modelCode);
                newModel.setCrtOrgId(user.getCrtOrgId());
                newModel.setOprId(user.getId());
                newModel.setBrandCode(brandCode);
                newModel.setStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                newModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(newModel);

                bizTmpService.saveBizTmp(newModel, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        newModel.getStatus(), newModel.getAuditStatus(), newModel.getId(), "", null, null, null);
            }

        } else {
            for (int i = 0; i < list.size(); i++) {
                BTermModelInfo newModel = new BTermModelInfo();
                BeanUtils.copyProperties(list.get(i), newModel);
                //获取品牌代码
                String modelCode = BusinessContainer.ModelCd_PREFIX + String.format("%06d", Integer.parseInt(sysSeqService
                        .updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.ModelCd_PREFIX, null)));

                newModel.setModelCode(modelCode);
                newModel.setBrandCode(brandCode);
                newModel.setCrtOrgId(user.getCrtOrgId());
                newModel.setOprId(user.getId());
                newModel.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                newModel.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(newModel);

                bizHisService.saveBizHisNew(newModel, newModel, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        newModel.getId(), null, null, null);
//                insertList.add(newBrand);
            }
        }
    }

    @Override
    public int countModel(String brandCode) {
        LambdaQueryWrapper<BTermModelInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BTermModelInfo::getBrandCode, brandCode);
        int count = this.count(queryWrapper);

        return count;
    }

    @Override
    public List<BTermModelInfo> getByBrandCode(String brandCode) {
        return bTermModelInfoMapper.selectByBrandCode(brandCode);
    }

    @Override
    public BTermModelInfo getModelName(String brandCode, String modelCode) {
        return bTermModelInfoMapper.getModelName(brandCode, modelCode);
    }
}
